package com.googlecode.tabletags.components;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.components.UIBean;
import org.apache.struts2.views.annotations.StrutsTagAttribute;
import org.apache.struts2.views.util.UrlHelper;

import com.opensymphony.xwork2.util.ValueStack;

/**
 * Abstract superclass of all components that require url attributes and
 * functionality.
 */
public abstract class AbstractURLComponent extends UIBean {
    protected HttpServletRequest req;
    protected HttpServletResponse res;

    // Url attributes
    protected String action;
    protected String method;
    protected String scheme;
    protected String namespace;
    protected boolean encode = true;
    protected String url;
    
    public AbstractURLComponent(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
        super(stack, request, response);
        this.req = request;
        this.response = response;
    }

    /**
     * @see com.opensymphony.webwork.components.UIBean#evaluateExtraParams()
     */
    protected void evaluateExtraParams() {
        super.evaluateExtraParams();

        Map<String, String> urlParams = new HashMap<String, String>();

        populateExtraParams(urlParams);

        if(action != null) {
            url = determineActionURL(action, namespace, method, req, res,
                    urlParams, scheme, true, encode);
        } else {
            StringBuffer urlParamString = new StringBuffer();
            if (url != null) {
                urlParamString.append(url);
            }
            UrlHelper.buildParametersString(urlParams, urlParamString);
            url = urlParamString.toString();
        }

        addParameter("url", url);
    }

    protected void populateExtraParams(Map<String, String> urlParams) {
    }
    
    @StrutsTagAttribute(description = "the url to post back to")
    public void setUrl(String url) {
        this.url = url;
    }

    @StrutsTagAttribute(description = "the action generate url for, if not using value")
    public void setAction(String action) {
        this.action = action;
    }

    @StrutsTagAttribute(description = "Whether to encode parameters", type = "Boolean", defaultValue = "true")
    public void setEncode(boolean encode) {
        this.encode = encode;
    }

    @StrutsTagAttribute(description = "The method of action to use")
    public void setMethod(String method) {
        this.method = method;
    }

    @StrutsTagAttribute(description = "The namespace to use")
    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    @StrutsTagAttribute(description = "Set scheme attribute")
    public void setScheme(String scheme) {
        this.scheme = scheme;
    }
}
